package generator.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import generator.domain.Supplier;
import generator.domain.SysRole;
import generator.domain.SysUser;
import generator.service.SupplierService;
import generator.utis.Constants;
import generator.utis.PageSupport;
import generator.utis.UploadUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Description: TODO
 * @author: 李展鹏
 * @date: 2024年04月30日8:57
 */
@Controller
@RequestMapping("/supplier")
public class SupplierController {
    private Logger logger=Logger.getLogger(SupplierController.class);
    @Resource
    private SupplierService supplierService;
    @RequestMapping("/list")
    public String getSupplierList(){

        return "supplier/list";
    }

    /**
     * 分页
     * @param model
     * @param querySupCode
     * @param querySupCode
     * @param pageIndex
     * @return
     */
    @GetMapping("/list")
    public String getSupplierList(Model model, String querySupName, String querySupCode
            , @RequestParam(defaultValue = "1") Integer pageIndex){
        List<Supplier> supplierList=null;
        try {
            //设置页面容量
            int pageSize= Constants.pageSize;
            //总数量(表)
            int totalCount= supplierService.getSupplieCount(querySupName, querySupCode);
            //总页数
            PageSupport pages=new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount=pages.getTotalPageCount();
            //控制首页和尾页
            if (pageIndex>totalPageCount){
                throw new RuntimeException("页码不正确");
            }
            supplierList=supplierService.getSupplieList(querySupName, querySupCode,pageIndex,pageSize);
            model.addAttribute("supplierList",supplierList);
//            List<SysRole> roleList=null;
//            roleList=sysRoleService.getRoleList();
//            model.addAttribute("roleList",roleList);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("用户列表接口访问失败!");
            return "redirect:/supplier/toSysError";
        }
        return "supplier/list";
    }
    @GetMapping("/view/{id}")
    public String supplierView(@PathVariable Integer id, Model model){
        logger.debug("根据id查询用户详情"+id);
        Supplier supplier=supplierService.getSupplierById(id);
        model.addAttribute(supplier);
        return "supplier/view";
    }

    /**
     * 跳转到添加页面
     * @param request
     * @return
     */
    @GetMapping(value = "/toAdd")
    public String toAdd(HttpServletRequest request){
        return "supplier/add";
    }

    /**
     * 添加及文件上传
     * @param supplier
     * @param session
     * @param request
     * @param attachs
     * @return
     * @throws IOException
     */
    @PostMapping("/add")
    public String add(Supplier supplier, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "attachs",required = false) MultipartFile[] attachs) throws IOException {
        String companyLicPicPath = null;
        String orgCodePicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("static" + File.separator + "uploadfiles");
        logger.info("uploadFile path  ======================>" + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                    companyLicPicPath = UploadUtil.uploadImage(attach);
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                    orgCodePicPath = UploadUtil.uploadImage(attach);
                }
                /*String oldFileName = attach.getOriginalFilename();//原文件名
                log.info("uploadFile oIdFileName======================>" + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);//原文件文件后缀
                log.debug("uploadFile prefix======================>" + prefix);
                int filesize = 5000000;
                log.debug("uploadFile filesize======================>" + attach.getSize());
                if (attach.getSize() > filesize) {//上传大小不得超过500K
                    request.setAttribute(errorInfo, " * 上传文件大小不得超过500K");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {//上传文件格式不正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg";
                    log.debug("new fileName======================>" + attach.getName());
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, " * 上传文件失败");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = File.separator + "static" + File.separator
                                + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = File.separator + "static" + File.separator
                                + "uploadfiles" + File.separator + fileName;
                    }
                    log.debug("idPicPath======================>" + idPicPath);
                    log.debug("workPicPath======================>" + workPicPath);*/
            } else {
                request.setAttribute(errorInfo, " * 上传图片格式不正确");
                flag = false;
            }
        }
        if (flag) {
            supplier.setCreateduserid(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
            supplier.setCompanylicpicpath(companyLicPicPath);
            supplier.setOrgcodepicpath(orgCodePicPath);
            if (supplierService.save(supplier)) {
                return "redirect:/supplier/list";
            }
        }
        return "supplier/add";
    }

    /**
     * 跳转到修改页面
     * @param uid
     * @param model
     * @return
     */
    @GetMapping("/toUpdate/{uid}")
    public String toUpdate(@PathVariable Integer uid,Model model){
        logger.debug("跳转到修改用户信息页面");
        Supplier supplier=supplierService.getById(uid);
        model.addAttribute("supplier",supplier);
        return "supplier/update";
    }

    /**
     * 修改操作
     * @param supplier
     * @param session
     * @return
     */
    @PostMapping("/update")
    public String modifySave(Supplier supplier,HttpSession session){
        supplier.setUpdateduserid(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if (supplierService.updateById(supplier)){
            return "redirect:/supplier/list";
        }
        return "supplier/update";
    }

    /**
     * 删除
     * @param supId
     * @return
     */
    @DeleteMapping("del/{supId}")
    @ResponseBody
    public String del(@PathVariable Long supId){
        JSONObject jsonObject = new JSONObject();
        Supplier supplier=new Supplier();
        supplier.setId(supId);
        supplier.setStatus(false);
        Boolean b = supplierService.updateById(supplier);
        try{
            jsonObject.put("delResult",b.toString());
        }catch(Exception e){
            jsonObject.put("delResult","notexist");
        }
        return jsonObject.toJSONString();
    }

    @GetMapping("/userExist")
    @ResponseBody
    public String userExist(String supname){
        JSONObject jsonObject = new JSONObject();
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supName",supname);
        Supplier supplierServiceOne = supplierService.getOne(queryWrapper);
        try{
            if (supplierServiceOne == null) {
                jsonObject.put("exist",0);
            }else {
                jsonObject.put("exist",1);
            }
        }catch(Exception e){
            jsonObject.put("exist",-1);
        }
        return jsonObject.toJSONString();
    }
}
